
import re

from django.http import JsonResponse
from django_redis import get_redis_connection
from rest_framework import serializers

from plumes.models import Article
from qas.models import Reply, Question
from qas.serializers import LabelSerializer
from recruitments.models import Enterprise
from users.models import User

class CreateUserSerializer(serializers.ModelSerializer):
    """管理员序列化器类"""
    # 注意：模型类中有，但是自己想重新进行定义的字段，也可以这样直接进行添加
    username = serializers.CharField(label='用户名')
    # 注意：模型类中没有，而序列化器类中又需要的字段，可以自己直接进行添加，但自己添加的字段也要放到 fields 中
    sms_code = serializers.CharField(label='验证码', write_only=True)
    token = serializers.CharField(label='JWT Token', read_only=True)

    # allow = serializers.BooleanField(label='是否勾选协议',write_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'sms_code', 'token', 'avatar')

        extra_kwargs = {
            'username': {
                'min_length': 1,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许1-20个字符的用户名',
                    'max_length': '仅允许1-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的用户名',
                    'max_length': '仅允许8-20个字符的用户名',
                }
            },
            'avatar': {
                'read_only': True
            },
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        # 手机号是否重复
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已存在')

        return value

    def validate_username(self,value):
        count = User.objects.filter(username=value).count()
        if count > 0:
            raise serializers.ValidationError('用户已存在')
        return value

    def validate(self, data):
        """注册用户信息保存"""
        # 短信验证码检验
        redis_conn = get_redis_connection('verify_code')
        mobile = data['mobile']
        sms_code_redis = redis_conn.get('sms_%s' % mobile)

        if not sms_code_redis:
            return JsonResponse({'code': 400,
                                 'message': '无效的短信验证码'})

        if data['sms_code'] != sms_code_redis:
            return JsonResponse({'code': 400,
                                 'message': '短信验证码错误'})

        return data

    def create(self, validated_data):
        # 获取登录用户 user
        del validated_data['sms_code']

        user = User.objects.create_user(**validated_data)

        # 服务器生成 jwt token, 保存当前用户的身份信息
        from rest_framework_jwt.settings import api_settings

        # 组织 payload 数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成 jwt token 数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织 payload 数据
        payload = jwt_payload_handler(user)
        # 生成 jwt token
        token = jwt_encode_handler(payload)

        # 给 user 对象增加临时属性，保存 jwt token 的数据
        user.token = token

        return user


class ReplySerializer(serializers.ModelSerializer):
    # answer_question = serializers.
    class Meta:
        model = Reply
        fields = '__all__'

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'

class QuestSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField(many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        fields = '__all__'


class EnterpriseSerializer(serializers.ModelSerializer):
    recruits = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    class Meta:
        model = Enterprise
        fields = '__all__'


class PersonSerializer(serializers.ModelSerializer):
    labels = LabelSerializer(many=True)
    questions = QuestSerializer(many=True)
    answer_question = serializers.SerializerMethodField()
    enterpises = EnterpriseSerializer(many=True)
    collected_articles = serializers.SerializerMethodField()  # 多对多关系
    username = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'realname', 'birthday', 'sex', 'avatar', 'website', 'email',
                  'city', 'address', 'labels', 'questions', 'answer_question', 'collected_articles', 'enterpises']

        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True

            },
        }

    # 重写create方法
    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

    def get_answer_question(self, obj):
        reply = Reply.objects.filter(user=obj)
        return ReplySerializer(reply, many=True).data

    def get_collected_articles(self, obj):
        # articles = Article.objects.filter(user=obj)
        articles = obj.collected_articles.all()
        return ArticleSerializer(articles, many=True).data

